package oot.activity;

import java.util.ArrayList;

import oot.data.Connection;
import oot.data.JSonPaser;
import oot.data.User;
import oot.tab.activity.R;
import oot.view.HeadTab;
import ott.adapter.FollowerAdapter;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

public class ListFollowersActivity extends Activity {
	private ArrayList<User> listFollowUser;
	private PullToRefreshListView listView;
	private String get_userid;
	private int paging = 1;
	FollowerAdapter followerAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.listfollowers);
		listFollowUser = new ArrayList<User>();
		followerAdapter = new FollowerAdapter(listFollowUser,
				getApplicationContext());
		listView = (PullToRefreshListView) findViewById(R.id.list_followers);
		listView.getRefreshableView().setBackgroundResource(R.drawable.bgconor);
		listView.getRefreshableView().setAdapter(followerAdapter);
		listView.getRefreshableView().setCacheColorHint(0);
		HeadTab h = new HeadTab(this);
		h.createHeadTabAction("ListFollowers");
		listView.setOnRefreshListener(new OnRefreshListener<ListView>() {

			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				paging = 1;
				if (listFollowUser != null) {
					listFollowUser.clear();
				} else {
					listFollowUser = new ArrayList<User>();
				}
				getListFollowers();
			}
		});

		listView.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {

			@Override
			public void onLastItemVisible() {
				getListFollowers();
			}
		});

		get_userid = getIntent().getStringExtra("get_userid");

		getListFollowers();

	}

	public void getListFollowers() {
		RequestParams requestParams = new RequestParams();
		requestParams.put("get_userid", get_userid);
		requestParams.put("paging", "" + paging);
		Connection.post("follows/followers", requestParams,
				new AsyncHttpResponseHandler() {
					@Override
					public void onSuccess(String res) {
						super.onSuccess(res);
						if (res != null) {
							listFollowUser = JSonPaser.listFollowers(res,
									listFollowUser);
							if (listFollowUser != null) {
								followerAdapter.notifyDataSetChanged();
								listView.onRefreshComplete();
								paging++;
							}
						}else{
							listView.onRefreshComplete();
						}
					}

					@Override
					public void onFailure(Throwable arg0, String res) {
						super.onFailure(arg0, res);
						listView.onRefreshComplete();
					}
				});
	}
}
